package com.example.demo.controller.usercontroller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.Result;
import com.example.demo.entity.Article;
import com.example.demo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 获取文章列表
     */
    @GetMapping("/list")
    public Result<List<Article>> list(@RequestParam(required = false) String category) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        // 只查询已发布的文章
        wrapper.eq(Article::getStatus, 1);
        // 如果指定了分类，则按分类查询
        if (category != null && !category.isEmpty()) {
            wrapper.eq(Article::getCategory, category);
        }
        // 按创建时间倒序排序
        wrapper.orderByDesc(Article::getCreateTime);
        
        List<Article> list = articleService.list(wrapper);
        return Result.success(list);
    }

    /**
     * 获取文章详情
     */
    @GetMapping("/{id}")
    public Result<Article> getArticle(@PathVariable Long id) {
        Article article = articleService.getById(id);
        if (article == null || article.getStatus() != 1) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
        return Result.success(article);
    }

    /**
     * 增加文章阅读量
     */
    @GetMapping("/view/{id}")
    public Result<Void> incrementViews(@PathVariable Long id) {
        boolean success = articleService.incrementViews(id);
        return success ? Result.success() : Result.error(ErrorCode.SYSTEM_ERROR);
    }
} 